package com.stxx.stiot2.event.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.stxx.framwork.constants.SceneActionType;
import com.stxx.stiot2.domain.EventLog;
import com.stxx.stiot2.domain.Scene;
import com.stxx.stiot2.domain.Terminal;
import com.stxx.stiot2.domain.ext.SceneAction;
import com.stxx.stiot2.event.dto.P2tMsg;
import com.stxx.stiot2.event.dto.T2pMsg;
import com.stxx.stiot2.gateway.face.GatewayServer;
import com.stxx.stiot2.utils.ServerUtils;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class ActionFlowTask implements Runnable{
    private List<SceneAction> actions;
    private T2pMsg message;
    private Integer sceneId;

    public ActionFlowTask(Integer sceneId,List<SceneAction> actions, T2pMsg message) {
        this.sceneId = sceneId;
        this.actions = actions;
        this.message = message;
    }
    @Override
    public void run() {
        actions.forEach(action->{
            if (action.getDelay() > 0) {
                try {
                    Thread.sleep(action.getDelay() * 1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            EventLog eventLog = new EventLog();
            eventLog.setActionType(action.getActionType());
            eventLog.setId(UUID.randomUUID().toString().replace("-",""));
            eventLog.setEventTime(LocalDateTime.now());
            eventLog.setName(action.getName());
            eventLog.setSceneId(sceneId);
            eventLog.setTerminalCode(message.getTerminalCode());
            eventLog.setParams(action.getParams());
            try {
                if(!StrUtil.isAllNotEmpty(action.getGatewayCode(),action.getTerminalCode())){
                    eventLog.setSuccess(false);
                    eventLog.setDesc("网络关或终端不存在");
                }else {
                    P2tMsg p2tMsg = new P2tMsg();
                    p2tMsg.setType(action.getActionType().getValue());
                    p2tMsg.setProperties(action.getParams());
                    GatewayServer server = ServerUtils.getGatewayUtils().getGateway(action.getGatewayCode());
                    server.send(action.getGatewayCode(), action.getTerminalCode(),p2tMsg);
                    eventLog.setSuccess(true);
                    eventLog.setDesc("执行成功");
                }
            }catch (Exception e) {
                eventLog.setSuccess(false);
                e.printStackTrace();
            }
            try {
                ServerUtils.getEventLogService().insert(eventLog);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }
}

